#encoding:utf8 
from basesrer import BaseSrer
from BeautifulSoup import * 
import sys, logging

import chardet

kSrType = dict(
	book = 0,
	film = 1,
	music = 2,
	game = 3,
	)
reload(sys)
sys.setdefaultencoding('utf-8')

class DoubanSr(BaseSrer):
	S_URLBASE = [
		"http://www.douban.com/search?cat=1001&q=%s",	#book	
		"http://www.douban.com/search?cat=1002&q=%s",	#film	
		"http://www.douban.com/search?cat=1003&q=%s",	#music	
		"http://www.douban.com/search?cat=3144&q=%s",	#game	
	]
	def __init__(self, stype):
		self._bookinfo = dict()

		self._scodetype = None
		self._stypename = stype
		self._svalue = None

		if kSrType.has_key(stype):
			BaseSrer.__init__(self, self.S_URLBASE[kSrType[stype]])	
		else:
			raise "No this key!"


	def search(self, svalue):
		self._svalue = svalue
		ret = self.start_sr(self.get_srurl(svalue))

		self._scodetype = chardet.detect(ret)

		soup = BeautifulSoup(ret)
		rlist= soup.findAll("div", {"class":"result"})
		func = getattr(self, "_chk_"+self._stypename)
		func(rlist)

	def _chk_book(self, resultlist):


		if len(resultlist) == 0:
			logging.error("Find noting!")
			return 

		score = "unknow"
		isfound = False

		ret = resultlist[0]
		score = self._get_bookscore(ret)

		if score == "unknow":
			logging.error("Not find the search result %s--->>"%self._svalue)
		else:
			logging.info("Find the search result %s 's score is %s.--->>"%(self._svalue, score))
			
		self._bookinfo["score"] = score
		

	def _get_bookscore(self, booktag):
		try:
			return booktag.find("div", {"class":"content"}).div.div.find("span", {"class":"rating_nums"}).text
		except:
			return "unknow"

	def get_ret(self):
		return self._bookinfo
